#!/usr/bin/env bash

#declare -r IMAGE_DIR=/mnt/rw/container
declare -r DOCKER_HUB=docker-hub:5000

function import_images()
{
  if [[ $# -eq 0 ]]
  then
    return 0
  fi

  if sudo test -d $1
  then
    echo -n ""
  else
    return 1
  fi

  local IMAGE_PATH=${1}
  local -ar FILES=($(sudo ls ${IMAGE_PATH}))
  local tmpfile=""
  for FILE in ${FILES[@]}
  do
    tmpfile=${IMAGE_PATH}/${FILE}
    if sudo test -f ${tmpfile}
    then
      # image
      echo "------------------------------------------------------------"
      echo ">> importing image file ${tmpfile}..."
      sudo docker load -i ${tmpfile}
      echo ""
    else
      # directory
      import_images ${tmpfile}
    fi
  done
}

function clean_image()
{
  echo ""
  echo "Clear images exists except for registry..."
  docker images | grep -v '^registry\ ' | awk 'NR>1{cmd="docker rmi "$1":"$2; system(cmd)}'
  echo ""
}

function retag_image()
{
  echo ""
  echo "Retag images to registry ${DOCKER_HUB}"
  #docker images | grep -v '^registry\ ' | awk 'NR>1{cmd="docker tag "$1":"$2" ${DOCKER_HUB}/"$1":"$2; system(cmd)}'
  docker images | awk 'NR>1{cmd="docker tag "$1":"$2" docker-hub:5000/"$1":"$2"; echo -n ."; system(cmd)}'
  echo ""
  echo ""
}

function push_image()
{
  echo "Push images to registry ${DOCKER_HUB}"
  docker images | grep "^${DOCKER_HUB}" | awk '{cmd="docker push "$1":"$2"; echo "; system(cmd)}'
  echo ""
}

###### main #######################
function show_usage()
{
  echo "To load all docker images, push them to registry, delete them finally."
  echo "Exporting images from registry if you want, run registry.sh -e <image> <directory>"
  echo ""
  echo "Usage: load-images-huge.sh <directory...>"
  echo ""
  echo "  directory: one or more directory specified."
  echo ""
  echo ""
}

if [ $# -eq 0 ]; then
  show_usage
  exit 1
fi

while [ -n "$1" ]; do
  echo "*************************************************************"
  echo "Import container image files from directory $1..."
  echo "*************************************************************"
  import_images "$1"
  echo ""
  echo ""
  shift
done
retag_image
push_image
clean_image
